package com.ebraga.trackerclub.android.util;

import java.io.InputStream;
import java.net.URL;
import java.util.List;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.AsyncTask;

import com.ebraga.trackerclub.android.exception.BackofficeUtilException;
import com.ebraga.trackerclub.android.util.webservice.HTTPSAndroidClientWrapper;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;

public class WebServiceTask<E> extends AsyncTask<String, Integer, String> {
	 
    private List<E> lstObject;
    private String requestMethod;
    private Context mContext;
    private HTTPBasicAuthFilter httpBasicAuthFilter;
    private HTTPSAndroidClientWrapper<E> clientWrapper;
    
    public WebServiceTask(Context mContext, String requestMethod) {
    	this.requestMethod  = requestMethod;
    	this.mContext = mContext;
    	
    	try {
    		clientWrapper = androidClientWrapper();
		} catch (Exception e) {
			e.printStackTrace();
		} 	
		
    }
    

	private HTTPSAndroidClientWrapper<E> androidClientWrapper()
			throws BackofficeUtilException {
		
		InputStream certificateStreamP12 	= loadCertificateDataP12();
		String keyStorePasswordP12 			= null;
		
		if (certificateStreamP12 != null) {
			keyStorePasswordP12 		= ISmartServiceConstants.WEBSERVICE_CERTIFICATE.KEY_STORE_PASSWORD;
		}
		
		InputStream certificateStreamJks 	= loadCertificateDataJks();
		String keyStorePasswordJks 			= null;
		
		if (certificateStreamJks != null) {
			keyStorePasswordJks 		= ISmartServiceConstants.WEBSERVICE_CERTIFICATE.JKS_PASSWORD;
		}
				
		
		HTTPSAndroidClientWrapper<E> clientWrapper;
		clientWrapper = new HTTPSAndroidClientWrapper<E>();
		//clientWrapper = new HTTPSAndroidClientWrapper<E>(null, null, httpBasicAuthFilter);
		
		return clientWrapper;
		
	}    
    
	/*
	 * TODO Está com um problema que no primeiro acesso o serviço retorna um erro.
	 * Precisamos verificar e corrigir o problema. Por falta de tempo o Thiago Maior solicitou fazer duas chamadas.  
	 */
	private void bugFirstAccess(HTTPSAndroidClientWrapper<E> clientWrapper, URL domain) {
		
		try {
			clientWrapper.doGet(domain.toString());
		} catch (Exception e) {
			e.printStackTrace();
		} 	
		
	}
	
    
    protected String doInBackground(String... urls) {
    	String result = null;
		
		try {

			URL domain = new URL(urls[0]);
			
			//bugFirstAccess(clientWrapper, domain);
			
			clientWrapper = androidClientWrapper();
			
			if (requestMethod == ISmartServiceConstants.REQUEST_METHOD.GET) {
				result = clientWrapper.doGet(domain.toString());
			} else if (requestMethod == ISmartServiceConstants.REQUEST_METHOD.POST) {
				result = clientWrapper.doPost(domain.toString(), lstObject);
			} else if (requestMethod == ISmartServiceConstants.REQUEST_METHOD.PUT) {
				result = clientWrapper.doPut(domain.toString(), lstObject);
			} else if (requestMethod == ISmartServiceConstants.REQUEST_METHOD.DELETE) {
				result = clientWrapper.doPut(domain.toString(), lstObject);
			}
			

		} catch (Exception e) {
			result = e.getMessage();
		} 		
		
        return result;
    }



    @Override
    protected void onPostExecute(String response) {
    	//UtilView.showMessage(mContext, response);
         
    }
    

	private InputStream loadCertificateDataP12() {
		return loadCertificate("sistema_geolocalizacao.p12");
	}

	
	private InputStream loadCertificateDataJks() {
		return loadCertificate("backoffice_proxy.bks");
	}
    	

	private InputStream loadCertificate(String certName) {
		InputStream certificateStream = null;
		
		if (mContext == null) {
			return null;
		}
		
		try {		
			AssetManager assetManager = mContext.getAssets();
			certificateStream = assetManager.open(certName);
		
		} catch (Exception e) {
			// 
		}

		return certificateStream;
	}    

	public List<E> getLstObject() {
		return lstObject;
	}

	public void setLstObject(List<E> lstObject) {
		this.lstObject = lstObject;
	}

	public HTTPBasicAuthFilter getHttpBasicAuthFilter() {
		return httpBasicAuthFilter;
	}

	public void setHttpBasicAuthFilter(HTTPBasicAuthFilter httpBasicAuthFilter) {
		this.httpBasicAuthFilter = httpBasicAuthFilter;
	}


}
